<template>
	<view class="form">
		<u-form :model="form" :rules="rules" labelWidth="110" ref="setForm">
			<u-form-item label="乡镇/街道 :" prop="level2Code" borderBottom="true" @click="level2CodeListShow()">
				<u-input v-model="form.level2Name" :disabled="true" disabledColor="#ffffff" border="none" placeholder="点击选择" />
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="村/社区 :" prop="level3Code" borderBottom="true" @click="level3CodeListShow()">
				<u-input v-model="form.level3Name" :disabled="true" disabledColor="#ffffff" border="none" placeholder="点击选择" />
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="组别 :" prop="houseGroup" borderBottom="true">
				<u-input v-model="form.houseGroup" border="none" placeholder="请输入组别" @blur="queryRecent()"/>
			</u-form-item>
			<u-form-item label="门牌号 :" prop="houseNumber" borderBottom="true">
				<u-input v-model="form.houseNumber" border="none" placeholder="请输入门牌号" @blur="queryRecent()"/>
			</u-form-item>
			<u-form-item label="户主名 :" prop="houseHolder" borderBottom="true">
				<u-input v-model="form.houseHolder" border="none" placeholder="请输入户主名" />
			</u-form-item>
			<u-form-item label="是否常住 :" prop="permanent" borderBottom="true">
				<u-radio-group v-model="form.permanent" placement="row">
					<u-radio activeColor="#55aaff" v-for="(item, index) in radiolist" :key="index"
						:customStyle="{marginRight: '20px'}" :label="item.name" :name="item.value">
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="联系电话 :" prop="phone" borderBottom="true">
				<u-input v-model="form.phone" border="none" placeholder="请输入手机号码" />
			</u-form-item>
			<u-form-item label="现有服务商 :" prop="op" borderBottom="true" @click="opShow = true">
				<u-input v-model="form.op" :disabled="true" disabledColor="#ffffff" border="none" placeholder="点击选择" />
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="家庭消费额 :" prop="houseCConsume" borderBottom="true">
				<u-input v-model="form.houseCConsume" border="none" placeholder="请输入金额" />
				<u-text slot="right" type="info" text="元/月"></u-text>
			</u-form-item>
			<u-form-item label="现有套餐 :" prop="currentSet" borderBottom="true">
				<u-input v-model="form.currentSet" border="none" placeholder="例: 139智能安防" />
			</u-form-item>
			<u-form-item label="套餐到期时间 :" prop="menuExpireTime" borderBottom="true">
				<!-- <u-input v-model="form.menuExpireTime" :disabled="true" disabledColor="#ffffff" border="bottom" placeholder="点击选择" /> -->
				<picker mode="date" :value="getDate({format: true})" :start="startDate" :end="endDate" @change="bindMenuExpireTimeChange">
					<view>{{form.menuExpireTime}}</view>
				</picker>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="营销照片 :" prop="siteImage" borderBottom="true">
				<u-upload :fileList="siteImageList" 
						@afterRead="afterRead" 
						@delete="deletePic" 
						name="1" 
						:maxCount="1"
						:multiple="true"
						v-model="form.siteImage">
				</u-upload>
			</u-form-item>
			<u-form-item label="详细地址 :" prop="address" borderBottom="true" @click="selectLocation()">
				<u-input v-model="form.address" :disabled="true" disabledColor="#ffffff" border="none" placeholder="点击选择" />
				<u-icon slot="right" name="map" color="#5555ff"></u-icon>
			</u-form-item>
			<u-form-item label="走访情况 :" prop="visitDetails">
				<u-textarea v-model="form.visitDetails" placeholder="请输入走访情况" count maxlength="255"></u-textarea>
			</u-form-item>
			<u-form-item label="备注 :" prop="remark">
				<u-textarea v-model="form.remark" placeholder="请输入备注内容" count maxlength="100"></u-textarea>
			</u-form-item>
			<u-divider text="以下内容成功营销时填写"></u-divider>
			<u-collapse :border = "false" @change="collapse= !collapse;">
				<u-collapse-item title="营销成功">
					<view>
						<u-form-item label="办理类别 :" prop="market.businessType" @click="businessTypeShow = true">
							<u-input v-model="form.market.businessType" :disabled="true" disabledColor="#ffffff" border="bottom" placeholder="点击选择" />
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item label="系统揽收人 :" prop="market.receiver">
							<u-input v-model="form.market.receiver" border="bottom" placeholder="系统揽收人" />
						</u-form-item>
						<u-form-item label="办理日期 :" prop="market.signDate" @click="signDateShow = true">
							<!-- <u-input v-model="form.market.signDate" :disabled="true" disabledColor="#ffffff" border="bottom" placeholder="点击选择" /> -->
							<picker mode="date" :value="getDate({format: true})" :start="startDate" :end="endDate" @change="bindSignDateChange">
								<view>{{form.market.signDate}}</view>
							</picker>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
						<u-form-item label="原套餐 :" prop="market.oldSet">
							<u-input v-model="form.market.oldSet" border="bottom" placeholder="例: 移动99" />
						</u-form-item>
						<u-form-item label="办理套餐 :" prop="market.signSet">
							<u-input v-model="form.market.signSet" border="bottom" placeholder="例: 139智能安防" />
						</u-form-item>
						<u-form-item label="系统优惠 :" prop="market.systemDiscount">
							<u-input v-model="form.market.systemDiscount" border="bottom" placeholder="例: XYZ" />
						</u-form-item>
						<u-form-item label="调账金额 :" prop="market.adjustAmount">
							<u-input v-model="form.market.adjustAmount" border="bottom" placeholder="例: 360" />
							<u-text slot="right" type="info" text="元"></u-text>
						</u-form-item>
						<u-form-item label="甩单编号 :" prop="market.orderCode">
							<u-input v-model="form.market.orderCode" border="bottom" placeholder="例: 526700000" />
						</u-form-item>
						<u-form-item label="营销积分 :" prop="market.marketPoint">
							<u-input v-model="form.market.marketPoint" border="bottom" placeholder="例: 139" />
						</u-form-item>
						<u-form-item label="主卡 :" prop="market.masterCard">
							<u-input v-model="form.market.masterCard" border="bottom" placeholder="例: 19111111110" />
						</u-form-item>
						<u-form-item label="副卡1 :" prop="market.assistantCard1">
							<u-input v-model="form.market.assistantCard1" border="bottom" placeholder="例: 19111111111" />
						</u-form-item>
						<u-form-item label="副卡2 :" prop="market.assistantCard2">
							<u-input v-model="form.market.assistantCard2" border="bottom" placeholder="例: 19111111112" />
						</u-form-item>
						<u-form-item label="副卡3 :" prop="market.assistantCard3">
							<u-input v-model="form.market.assistantCard3" border="bottom" placeholder="例: 19111111113" />
						</u-form-item>
						<u-form-item label="副卡4 :" prop="market.assistantCard4">
							<u-input v-model="form.market.assistantCard4" border="bottom" placeholder="例: 19111111114" />
						</u-form-item>
					</view>
				</u-collapse-item>
			</u-collapse>
		</u-form>
		<u-button type="primary" 
				:hairline="false" 
				:disabled="submitLoading"
				:loading="submitLoading"
				customStyle="margin-top: 30px"
				text="提交"
				@click="submit">
		</u-button>
		<u-button type="error" 
				:hairline="true" 
				:disabled="resetLoading" 
				:loading="resetLoading"
				customStyle="margin-top: 10px"
				text="重置"
				@click="reset">
		</u-button>
		
		<!-- 乡镇/街道选择 -->
		<u-picker :show="level2CodeShow" 
			:columns="level2Columns" 
			:loading="level2CodeLoading"
			closeOnClickOverlay=true 
			keyName="name"
			@cancel="level2CodeShow = false"
			@close="level2CodeShow = false"
			@confirm="level2CodeConfirm()"></u-picker>
		<!-- 村/社区选择 -->
		<u-picker :show="level3CodeShow" 
			:columns="level3Columns" 
			:loading="level3CodeLoading"
			closeOnClickOverlay=true 
			keyName="name"
			@cancel="level3CodeShow = false"
			@close="level3CodeShow = false"
			@confirm="level3CodeConfirm()"></u-picker>
		<!-- 运营商选择 -->
		<u-picker :show="opShow" 
			:columns="opColumns" 
			closeOnClickOverlay=true
			@cancel="opShow = false"
			@close="opShow = false"
			@confirm="opConfirm()"></u-picker>
		<!-- 套餐到期时间选择 u-calendar月份过多导致加载过慢-->
		<!-- <u-calendar :show="expireTimeShow" mode="single" closeOnClickOverlay=true monthNum="48" showLunar
			@close="expireTimeShow = false"
			@confirm="expireTimeConfirm()"></u-calendar> -->
		<!-- 办理类别选择 -->
		<u-picker :show="businessTypeShow" 
			:columns="businessTypeColumns" 
			closeOnClickOverlay=true
			@cancel="businessTypeShow = false"
			@close="businessTypeShow = false"
			@confirm="businessTypeConfirm()"></u-picker>
		<!-- 办理日期选择 -->
		<!-- <u-calendar :show="signDateShow" mode="single" closeOnClickOverlay=true monthNum="2" showLunar
			@close="signDateShow = false"
			@confirm="signDateConfirm()"></u-calendar> -->
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import config from "@/common/config.js"
	export default {
		data() {
			return {
				level2CodeShow: false, //街道/乡镇show
				level2CodeLoading: false, //街道/乡镇loading
				level3CodeShow: false, //社区/村show
				level3CodeLoading: false, //社区/村loading
				radiolist: [{
						name: '是',
						value: 1
					},
					{
						name: '否',
						value: 0
					},
				],
				opShow: false, //运营商show
				businessTypeShow: false, //业务类别show
				expireTimeShow: false, //超期时间show
				signDateShow: false, //业务办理日期show
				level2Columns: [],
				level3Columns: [],
				opColumns: [
					['电信', '移动', '联通', '广电', '卫星锅', '其他']
				],
				collapse: false,
				businessTypeColumns: [
					['新装', '保存', '其他']
				],
				siteImageList: [],
				submitLoading: false,
				resetLoading: false,
				inputDisabled: true,
				form: {
					id: '',
					level2Code: '',
					level2Name: '',
					level3Code: '',
					level3Name: '',
					houseGroup: '',
					houseNumber: '',
					houseHolder: '',
					permanent: '',
					phone: '',
					op: '',
					houseCConsume: '',
					currentSet: '',
					menuExpireTime: this.getDate({format: true}),
					visitDetails: '',
					siteImage: '',
					address: '',
					remark: '',
					longitude: '',
					latitude: '',
					market: { //营销成功
						businessType: '', //业务类别
						receiver: '', //系统揽收人
						signDate: this.getDate({format: true}), //办理日期
						oldSet: '', //原套餐
						signSet: '', //办理套餐
						systemDiscount: '', //系统折扣
						adjustAmount: '', //调账金额
						orderCode: '', // 甩单编号
						marketPoint: '', //积分
						masterCard: '', //主卡
						assistantCard1: '', //副卡1
						assistantCard2: '', //副卡2
						assistantCard3: '', //副卡3
						assistantCard4: '' //副卡4
					}
				},
				rules: {
					level2Code: {
						type: 'number',
						required: true,
						message: '请选择乡镇/街道'
					},
					level3Code: {
						type: 'number',
						required: true,
						message: '请选择村/社区'
					},
					houseGroup: {
						type: 'number',
						required: true,
						message: '组别不能为空且必须为数字',
						trigger: ['change', 'blur']
					},
					houseNumber: {
						type: 'number',
						required: true,
						message: '门牌号不能为空且必须为数字',
						trigger: ['change', 'blur']
					},
					houseHolder: {
						type: 'string',
						required: true,
						message: '户主名不能为空',
						trigger: ['change', 'blur']
					},
					permanent: {
						type: 'number',
						required: true,
						message: '请选择常住类型'
					},
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur']
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							trigger: ['change', 'blur']
						}
					],
					op: {
						type: 'string',
						required: true,
						message: '请选择运营商'
					},
					houseCConsume: {
						type: 'number',
						required: true,
						message: '家庭支出额不能为空且必须为数字',
						trigger: ['change', 'blur']
					},
					currentSet: {
						type: 'string',
						required: true,
						message: '现有套餐不能为空',
						trigger: ['change', 'blur']
					},
					menuExpireTime: {
						type: 'string',
						required: true,
						message: '请选择套餐到期时间'
					},
					siteImage: {
						type: 'string',
						required: true,
						message: '请上传营销照片'
					},
					address:{
						type: 'string',
						required: true,
						message: '请选择地理位置'
					}
				},
				userInFo: {},
			}
		},
		onReady() {
			this.$refs.setForm.setRules(this.rules);
		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			}
		},
		onLoad() {
			// this.getUserinfo();
		},
		beforeMount() {
			var _that = this
			uni.getStorage({
				key:'level2Code',
				success(res) {
					_that.form.level2Code = res.data
				}
			})
			uni.getStorage({
				key:'level2Name',
				success(res) {
					_that.form.level2Name = res.data
				}
			})
			uni.getStorage({
				key:'level3Code',
				success(res) {
					_that.form.level3Code = res.data
				}
			})
			uni.getStorage({
				key:'level3Name',
				success(res) {
					_that.form.level3Name = res.data
				}
			})
		},

		methods: {
			level2CodeListShow(){
				this.level2CodeLoading = true
				this.level2CodeShow = true
				let params = {
					params: {
						level: 2,
						parentId: 1
					}
				}
				this.$u.api.set.regionList(params).then((res) => {
					if(res.code === 0){
						this.level2Columns = [[...res.data]]
					}
				});
				this.level2CodeLoading = false
			},
			level3CodeListShow(){
				if(!this.form.level2Code){
					this.$refs.uToast.show({
						message: '请先选择乡镇/街道',
						duration: 1000
					})
					return;
				}
				this.level3CodeLoading = true
				this.level3CodeShow = true
				let params = {
					params: {
						level: 3,
						parentId: this.form.level2Code
					}
				}
				this.$u.api.set.regionList(params).then((res) => {
					if(res.code === 0){
						this.level3Columns = [[...res.data]]
					}
				});
				this.level3CodeLoading = false
			},
			level2CodeConfirm(e){
				this.level2CodeShow = false
				this.form.level2Code = e && e.value[0].id
				this.form.level2Name = e && e.value[0].name
				this.level3Columns = []
				this.form.level3Code = ''
				this.form.level3Name = ''
				uni.setStorage({
					key: 'level2Code',
					data: this.form.level2Code
				})
				uni.setStorage({
					key: 'level2Name',
					data: this.form.level2Name
				})
			},
			level3CodeConfirm(e){
				this.level3CodeShow = false;
				this.form.level3Code = e && e.value[0].id
				this.form.level3Name = e && e.value[0].name
				uni.setStorage({
					key: 'level3Code',
					data: this.form.level3Code
				})
				uni.setStorage({
					key: 'level3Name',
					data: this.form.level3Name
				})
			},
			queryRecent(){
				let _that = this
				if(this.form.level2Code && this.form.level3Code && this.form.houseGroup && this.form.houseNumber){
					let params = {
						params: {
							level2Code: this.form.level2Code,
							level3Code: this.form.level3Code,
							houseGroup: this.form.houseGroup,
							houseNumber: this.form.houseNumber
						}
					}
					this.$u.api.set.queryRecent(params).then((res) => {
						this.$refs.setForm.clearValidate()
						if (res.code === 0  && res.data !== null) {
							console.log('res.data',res.data)
							_that.form.id = res.data.id,
							_that.form.level2Code = res.data.level2Code,
							_that.form.level2Name = res.data.level2Name,
							_that.form.level3Code = res.data.level3Code,
							_that.form.level3Name = res.data.level3Name,
							_that.form.houseGroup = res.data.houseGroup,
							_that.form.houseNumber = res.data.houseNumber,
							_that.form.houseHolder = res.data.houseHolder,
							_that.form.permanent = res.data.permanent,
							_that.form.phone = res.data.phone,
							_that.form.op = res.data.op,
							_that.form.houseCConsume = res.data.houseCConsume,
							_that.form.currentSet = res.data.currentSet,
							_that.form.menuExpireTime = _that.getDate({format: true}),
							_that.form.visitDetails = res.data.visitDetails,
							_that.form.siteImage = res.data.siteImage,
							_that.form.address = res.data.address,
							_that.form.remark = res.data.remark,
							_that.form.longitude = res.data.longitude,
							_that.form.latitude = res.data.latitude
							_that.siteImageList.push({
								status: 'success',
								message: '',
								url: res.data.siteImage
							})
						}
					})
				}
			},
			opConfirm(e){
				this.opShow = false;
				this.form.op = e.value[0]
			},
			bindMenuExpireTimeChange(e) {
				this.form.menuExpireTime = e.detail.value
			},
			bindSignDateChange(e){
				this.form.market.signDate = e.detail.value
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 2;
				} else if (type === 'end') {
					year = year + 20;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			selectLocation() {
				let _that = this
				uni.getSetting({
					success(res) {
						if(res.authSetting['scope.userLocation'] === true){
							uni.chooseLocation({
								success: function(res) {
									_that.form.longitude = res.longitude;
									_that.form.latitude = res.latitude;
									_that.form.address = res.address
								}
							});
						}else{
							uni.showModal({
								title: '即将跳转授权页面',
								content: '您没有授权获取您的位置',
								success(res){
									if(res.confirm){
										uni.openSetting()
									}
								}
							})
						}
					}
				})
			},
			// 删除图片
			deletePic(event) {
				this.siteImageList.splice(event.index, 1)
				this.form.siteImage = ''
			},
			// 新增图片
			async afterRead(event) {
				let _that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = _that.siteImageList.length
				lists.map((item) => {
					_that.siteImageList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _that.uploadFilePromise(lists[i].url)
					let item = _that.siteImageList[fileListLen]
					_that.siteImageList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url
					}))
					fileListLen++
				}
				_that.form.siteImage = _that.siteImageList[0].url
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/smart/mini/file/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							setTimeout(() => {
								resolve(data.data)
							}, 1000)
						}
					});
				})
			},
			businessTypeConfirm(e){
				this.form.market.businessType = e.value[0]
				this.businessTypeShow = false;
			},
			signDateConfirm(e){
				this.signDateShow = false;
				this.form.market.signDate = e[0]
			},
			submit() {
				this.submitLoading = true
				this.$refs.setForm.validate().then(res => {
					this.houseSetUpload()
					this.submitLoading = false
				}).catch(errors => {
					this.submitLoading = false
				})
			},
			houseSetUpload() {
				let params = {
					...this.form
				}
				this.$u.api.set.setRecordAdd(params).then((res) => {
					if (res.code === 0) {
						uni.showToast({
							title: '上传成功',
							duration: 2000,
						});
						setTimeout(function() {
							this.submitLoading = false
							uni.navigateBack();
						}, 700)
					} else {
						uni.showToast({
							title: e.msg,
							duration: 2000
						});
						setTimeout(function() {
							this.submitLoading = false
						}, 700)
					}
				}).catch(e => {
						uni.showToast({
							title: e.msg,
							duration: 2000
						});
						setTimeout(function() {
							this.submitLoading = false
						}, 700)
				});
			},
			reset(){
				this.resetLoading = true
				this.level2Columns = []
				this.level3Columns = []
				this.siteImageList = []
				this.form.id = ''
				this.form.level2Code = ''
				this.form.level2Name = ''
				this.form.level3Code = ''
				this.form.level3Name = ''
				this.form.houseGroup = ''
				this.form.houseNumber = ''
				this.form.houseHolder = ''
				this.form.permanent = ''
				this.form.phone = ''
				this.form.op = ''
				this.form.houseCConsume = ''
				this.form.currentSet = ''
				this.form.menuExpireTime = this.getDate({format: true})
				this.form.visitDetails = ''
				this.form.siteImage = ''
				this.form.address = ''
				this.form.remark = ''
				this.form.longitude = ''
				this.form.latitude = ''
				this.form.market.businessType = ''
				this.form.market.receiver = ''
				this.form.market.signDate = this.getDate({format: true})
				this.form.market.oldSet = ''
				this.form.market.signSet = ''
				this.form.market.systemDiscount = ''
				this.form.market.adjustAmount = ''
				this.form.market.orderCode = ''
				this.form.market.marketPoint = ''
				this.form.market.masterCard = ''
				this.form.market.assistantCard1 = ''
				this.form.market.assistantCard2 = ''
				this.form.market.assistantCard3 = ''
				this.form.market.assistantCard4 = ''
				this.$refs.setForm.clearValidate()
				this.resetLoading = false
			}
		},
	}
</script>

<style lang="scss" scoped>
	.form {
		margin-top: 50rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
		padding: 0 10rpx 100rpx 10rpx;
	}

	.button {
		color: #ffffff;
		font-size: 32rpx;
		width: 80%;
		height: 80rpx;
		background: #1F87C6;
		box-shadow: 0rpx 0rpx 13rpx 0rpx rgba(15, 168, 250, 0.4);
		border-radius: 10rpx;
		line-height: 80rpx;
		text-align: center;
		margin: 50rpx auto 0;
	}

</style>
